<template>
  <el-dialog
    :visible.sync="visible"
    width="90%"
    title="新增"
    center
    :z-index="100005"
    modal-append-to-body
    :close-on-click-modal="false"
    class="bg-white rounded-xl shadow-2xl transform transition-all duration-300"
  >
    <template #title>
      <div class="flex items-center justify-between w-full">
        <div class="flex items-center">
          <i class="fa fa-image text-primary mr-2"></i>
          <span class="text-lg font-medium">写文</span>
        </div>
      </div>
    </template>

    <div class="p-6 space-y-6">
      <div class="bg-gray-50 rounded-lg p-5 shadow-sm">
        <el-form
          :model="itemObj"
          ref="queryForm"
          size="small"
          label-width="80px"
          class="space-y-4"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="itemObj.title"
              placeholder="请输入标题"
              clearable
              class="w-full max-w-md"
            />
          </el-form-item>
          <el-form-item label="封面地址" prop="coverurl">
            <el-input
              v-model="itemObj.coverurl"
              placeholder="封面地址"
              clearable
              class="w-full max-w-md"
            />
          </el-form-item>

          <!-- 多行文本框替代编辑器 -->
          <el-form-item label="内容编辑" prop="contents">
            <div class="fill-width">

              <el-row :gutter="12" style="margin: 0;" >
                <el-col :span="24" :md="12" :lg="12" :xl="12" :xs="24" :sm="24"  style="padding: 6px;">
                  <el-card class="thumbnail-card flex-col height-410" >
                    <template #header>代码编辑</template>
                    <div class="fill-width-height flex-col flex-1 ">
                      <AceEditor
                        v-model="itemObj.contents"
                        :mode="editorMode"
                        :height="'300px'"
                      />
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="24" :md="12" :lg="12" :xl="12" :xs="24" :sm="24" style="padding: 6px;">
                  <el-card class="thumbnail-card flex-col height-410" >
                    <template #header>实时预览</template>
                    <div class="fill-width-height flex-col flex-1 ">
                      <iframe id="previewFrame" class="fill-width-height border-0" :srcdoc="previewContent"></iframe>
                    </div>
                  </el-card>
                </el-col>
              </el-row>

            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="flex justify-end space-x-3 pt-4 border-t border-gray-100" style="margin-top: 10px;">
      <el-button
        @click="visible = false"
        class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors duration-200"
      >
        取消
      </el-button>
      <el-button
        type="primary"
        @click="submit"
        class="px-4 py-2 rounded-lg shadow hover:shadow-md transition-all duration-200"
      >
        提交
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {saveArticle, updateCoverUrl,upload} from "@/api/imgManage/writeArticles";
import html2canvas from "html2canvas";

export default {
  name: 'ImageCrawler',
  components: {
    AceEditor: () => import('./AceEditor')
  },
  props: {
    mode: {},
    item: {}
  },
  data() {
    return {
      selectImgDialogVisible: false,
      visible: false,
      itemObj: {
        title: '',
        coverurl: '',
        imagesUrls: [],
        contents: ''
      },
      editorMode: 'html',
      coverImgUrl: ''
    }
  },
  computed: {
    // 计算属性：处理预览内容，替换模板变量
    previewContent() {
      let content = this.itemObj.contents;
      return content?.replace('${itemObj.title}', this.itemObj.title || '文章标题');
    }
  },
  methods: {
    showDialog() {
      if(this.mode === 'add'){
        this.$set(this,'itemObj',Object.assign({}, {
          title: '',
          coverurl: '',
          imagesUrls: [],
          contents: ''
        }))
      } else if(this.mode === 'edit'){
        this.$set(this,'itemObj',Object.assign({}, this.item))
      }
      this.$nextTick(() => {
        this.visible = true
      })
    },
    // 将DataURL转换为Blob对象
    dataURLToBlob(dataURL) {
      const arr = dataURL.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);

      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }

      return new Blob([u8arr], {type: mime});
    },
    // 上传图像到服务器
    async uploadImage(dataURL, title) {
      try {
        // 将DataURL转换为Blob
        const blob = this.dataURLToBlob(dataURL);

        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', blob, `${title}.png`);
        // 发送请求到后端
        const response = await upload(formData);
        console.log('uploadResponse ', response)
        return response;
      } catch (error) {
        console.error('上传过程中出错:', error);
        throw error;
      }
    },
    downCover(id, title) {
      return new Promise((resolve, reject) => {
        const refs = document.getElementById(id)
        this.$modal.loading("正在截图中，请稍候...");

        // 替换所有图片的URL为你的代理URL
        const replaceImagesWithProxy = () => {
          const baseUrl = this.$config.urlFormat('/proxy',false)
          const images = refs.querySelectorAll('img');
          images.forEach( img => {
            if (img.src && img.src.startsWith('http') &&  !img.dataset.proxyConverted) {
              img.src = `${baseUrl}&url=${encodeURIComponent(img.src)}`
              // 设置成已转换
              img.dataset.proxyConverted = 'true';
            }
          });
        };
        replaceImagesWithProxy();

        setTimeout(() => {
          html2canvas(refs, {
            scale: 4,
            useCORS: true,
            allowTaint: true
          }).then(canvas => {
            // 获取原始图像数据
            const originalImage = new Image();
            originalImage.src = canvas.toDataURL("image/png");

            // 创建新的2.35:1画布
            originalImage.onload = () => {
              // 目标比例2.35:1
              const targetRatio = 2.35;
              const originalRatio = canvas.width / canvas.height;

              // 创建新画布
              const newCanvas = document.createElement('canvas');
              const ctx = newCanvas.getContext('2d');

              if (originalRatio < targetRatio) {
                // 原图比例小于2.35:1（更"高"），添加左右填充
                newCanvas.width = canvas.height * targetRatio;
                newCanvas.height = canvas.height;

                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);

                // 计算居中位置
                const offsetX = (newCanvas.width - canvas.width) / 2;

                // 绘制原始图像
                ctx.drawImage(
                  originalImage,
                  offsetX, 0,
                  canvas.width, canvas.height
                );
              } else {
                // 原图比例大于等于2.35:1（更"宽"），等比缩放
                newCanvas.width = canvas.width;
                newCanvas.height = canvas.width / targetRatio;

                // 计算居中位置
                const offsetY = (newCanvas.height - canvas.height) / 2;

                // 绘制白色背景
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, newCanvas.width, newCanvas.height);

                // 绘制原始图像
                ctx.drawImage(
                  originalImage,
                  0, offsetY,
                  canvas.width, canvas.height
                );
              }
              // 保存调整后的图像并下载
              this.coverImgUrl = newCanvas.toDataURL("image/png");
              // 上传图像
              this.uploadImage(this.coverImgUrl, title).then(async response => {
                console.log('上传成功:', response);
                // 可以在这里处理上传成功后的逻辑
                this.$message.success('封面上传成功');
                this.itemObj.coverurl = response.url
                this.$modal.closeLoading();
                resolve()
              }).catch(error => {
                console.error('上传失败:', error);
                this.$message.error('封面上传失败');
                this.$modal.closeLoading();
                reject()
              });

            };
          }).catch(e => {
            console.error(e)
            this.$modal.closeLoading()
          });
        },2000)
      });
    },
    submit() {
      this.$refs.queryForm.validate(async valid => {
        if (valid) {
          if(this.itemObj?.coverurl?.length === 0){
            await this.downCover('previewFrame', this.itemObj.title)
          }
          const res = await saveArticle(this.itemObj)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.visible = false
            this.$emit('callBack')
          } else {
            this.$message({
              type: 'error',
              message: '保存错误'
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: '请完善表单信息'
          })
          return false
        }
      })
    }
  },
  mounted() {
  }
}
</script>

<style scoped lang="scss">
// 导入Tailwind CSS
@tailwind utilities;

// 自定义工具类
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .flex-col {
    display: flex;
    flex-direction: column;
  }
  .tab-active {
    @apply text-primary border-primary;
  }
  .tab-inactive {
    @apply text-gray-500 hover:text-primary transition-colors;
  }
}

// 全局样式
::v-deep .el-dialog {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    padding: 18px 20px;
    background-color: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }

  .el-dialog__title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
  }
}

// 表单样式优化
::v-deep .el-form-item {
  margin-bottom: 18px;

  .el-form-item__label {
    color: #606266;
  }

  .el-input__inner {
    border-radius: 6px;
    height: 36px;
    line-height: 36px;
  }
}

#previewFrame{
  border: 1px solid #e3e3e3;
  border-radius: 10px;
}

.thumbnail-card {
  display: flex;
  flex-direction: column;

  ::v-deep .el-card__body {
    flex: 1;
  }
}

// 按钮样式优化
::v-deep .el-button {
  border-radius: 6px;
  padding: 8px 15px;

  &.el-button--primary {
    background-color: #409EFF;
    border-color: #409EFF;

    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }

  &.el-button--danger {
    background-color: #F56C6C;
    border-color: #F56C6C;

    &:hover {
      background-color: #f78989;
      border-color: #f78989;
    }
  }
}

// 文本框样式
::v-deep textarea {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  outline: none;
  resize: none;
}
</style>
